#include "SpriteSheet.h"

namespace binge
{

SpriteSheet::SpriteSheet(sf::Image* theImage, int theCols, int theRows, sf::Color theTranscolor)
{
    theImage->CreateMaskFromColor(theTranscolor);
    sprite.SetImage(*theImage);
    cols = theCols;
    rows = theRows;

    numFrames = cols * rows;
    frameWidth = sprite.GetImage()->GetWidth() / cols;
    frameHeight = sprite.GetImage()->GetHeight() / rows;

    index = 0;
    subRect = sf::IntRect(0, 0, frameWidth, frameHeight);
}

SpriteSheet::~SpriteSheet(void)
{

}

int
SpriteSheet::GetFrameIndex(void)
{
    return index;
}

void
SpriteSheet::SetFrameIndex(int theIndex)
{
    index = theIndex;

    int frameCol = index % cols;
    int frameRow = index / cols;

    int dx = frameCol * frameWidth - subRect.Left;
    int dy = frameRow * frameHeight - subRect.Top;

    subRect.Offset(dx, dy);
    sprite.SetSubRect(subRect);
}

bool
SpriteSheet::NextFrame(void)
{
    bool hasRestarted = false;
    int currentIndex = index + 1;

    if (currentIndex >= numFrames)
    {
        currentIndex = 0;
        hasRestarted = true;
    }
    SetFrameIndex(currentIndex);

    return hasRestarted;
}

sf::Sprite&
SpriteSheet::GetSprite(void)
{
    return sprite;
}

int
SpriteSheet::GetFrameWidth(void)
{
    return frameWidth;
}

int
SpriteSheet::GetFrameHeight(void)
{
    return frameHeight;
}

} // namespace
